import dayjs from 'dayjs';
import { formatOptions, xLabelStyle, yLabelStyle } from './formatter';
import type { Options, XType, YTypes, BaseNameDataObject } from './type';
import { formatDecimal } from './util';

interface YData extends BaseNameDataObject {
  type: 'line' | 'bar';
  barWidth?: number;
  tooltipTitles?: string[];
}

interface LineBarChartProps {
  options: Options;
  xType: XType;
  yTypes: YTypes;
  xData: number[] | string[];
  yData: YData[];
}

export const createLineBarOption = ({
  options,
  xType,
  yTypes,
  xData,
  yData
}: LineBarChartProps) => {
  // 格式化options
  options = formatOptions(options);

  // 设定距离
  // const { maxValue, minValue } = getMaxAndMin(yData.filter((item) => item.type === "bar"));
  // options.distance = getDistance(maxValue, minValue);

  return {
    // 暂时封存
    // grid: {
    //   left: 10 - options.distance, // 组件离容器左侧的距离
    //   right: 0, // 组件离容器右侧的距离(右侧也有y轴)
    //   top: 38, // 组件离容器上侧的距离(始终显示y轴名称)
    //   bottom: options.showLabel ? 0 : 10, // 组件离容器下侧的距离(不显示x轴标签时10)
    //   containLabel: true, // grid区域是否包含坐标轴的刻度标签
    // },
    grid: {
      left: 40, // 组件离容器左侧的距离
      right: 40, // 组件离容器右侧的距离(右侧也有y轴，40)
      top: 45, // 组件离容器上侧的距离(始终显示y轴名称，45)
      bottom: options.showLabel ? 25 : 10, // 组件离容器下侧的距离(不显示x轴标签时10)
      containLabel: false // grid区域是否包含坐标轴的刻度标签
    },
    tooltip: {
      trigger: 'axis', // 坐标轴触发，折线图等会使用类目轴的图表中使用
      showDelay: 0, // 显示延迟，添加显示延迟可以避免频繁切换，单位ms
      backgroundColor: 'rgba(0, 0, 0, 0.6)', // 背景颜色
      padding: 8,
      borderRadius: 6, // 边框圆角
      borderWidth: 0, // 边框宽度
      formatter: (params: any) => {
        // 副标题
        let subTitle = params[0].axisValue;
        if (xType === 'date') {
          subTitle = dayjs.unix(params[0].axisValue).format('MM/DD');
        } else if (xType === 'time') {
          subTitle = dayjs.unix(params[0].axisValue).format('MM/DD HH:mm');
        }
        const subTitleStr = `<div class="subtitle">${subTitle}</div>`;

        // 标题
        let titleStr = '';
        params.forEach((item: any) => {
          const series = yData[item.seriesIndex];
          const titles = series.tooltipTitles;
          if (titles?.length) {
            const title = titles[item.dataIndex];
            titleStr = `<div class="title">${title}</div>`;
          }
        });

        // 图例数据
        let itemStr = '';
        params.forEach((item: any) => {
          let number = item.value;
          let unit = '';
          if (yTypes[item.seriesType] === 'percent') {
            // number = (number * 100).toFixed(2);
            number = formatDecimal(number, options.percentPrecision as number);
            unit = '%';
          } else if (yTypes[item.seriesType] === 'number') {
            // if (number > 10000) {
            //   number = parseFloat((number / 10000).toFixed(1));
            //   unit = "万";
            // }
          }

          itemStr += `<div class="row">
            <div class="sample" style="background: ${item.color}"></div>
            <div class="name">${item.seriesName}：</div>
            <div class="value">
              <div class="value-inner">
                <span class="unit">${unit}</span>
                <span class="number">${number.toLocaleString()}</span>
              </div>
            </div>
          </div>`;
        });

        const str = `<div class="chart-tooltip line-bar">
          ${titleStr}
          ${subTitleStr}
          ${itemStr}
        </div>`;

        return str;
      },
      axisPointer: {
        // type: "shadow",
        // z: 0,
        // shadowStyle: {
        //   color: "rgba(237, 241, 253, 0.5)",
        //   width: "1",
        // },
        z: 1,
        lineStyle: {
          type: 'dashed',
          width: 2,
          color: '#92ACF2'
        }
      } // 坐标轴指示器配置项
    },
    color: [
      ...yData.filter((item) => item.type === 'line').map((item) => item.color),
      ...yData.filter((item) => item.type === 'bar').map((item) => item.color)
    ],
    xAxis: {
      type: 'category',
      triggerEvent: false, // 是否触发事件
      boundaryGap: true, // x坐标轴两边是否留白，不留白时，第一个和最后一个数据点会被遮挡
      axisLine: {
        show: true,
        lineStyle: {
          color: '#E5E6EC',
          type: 'solid'
        }
      }, // 坐标轴线
      axisTick: {
        show: false
      }, // 坐标轴刻度
      axisLabel: xLabelStyle(xType, options), // 坐标轴标签
      data: xData
    },
    yAxis: [
      {
        type: 'value',
        name: yData.find((item) => item.type === 'bar')?.name,
        nameLocation: 'end',
        nameTextStyle: {
          align: 'left',
          color: '#8F98B2',
          // padding: [0, 0, 3, 0 - options.distance],
          padding: [0, 0, 3, -40],
          fontSize: 12,
          lineHeight: 20,
          fontFamily: 'PingFang SC, sans-serif'
        },
        axisLabel: yLabelStyle(yTypes.bar, options), // 坐标轴标签
        splitLine: {
          show: true,
          lineStyle: {
            color: '#E5E6EC',
            type: 'dashed'
          }
        } // 分割线
      }, // 柱状图y轴固定在左边
      {
        type: 'value',
        name: yData.find((item) => item.type === 'line')?.name,
        nameLocation: 'end',
        nameTextStyle: {
          align: 'right',
          color: '#8F98B2',
          // padding: [0, 0 - 30, 3, 0],
          padding: [0, -40, 3, 0],
          fontSize: 12,
          lineHeight: 20,
          fontFamily: 'PingFang SC, sans-serif'
        },
        axisLabel: yLabelStyle(yTypes.line, options, 'right'), // 坐标轴标签
        splitLine: {
          show: false
        } // 分割线
      } // 折线图y轴固定在右边
    ],
    series: [
      ...yData
        .filter((item) => item.type === 'bar')
        .map((item) => {
          return {
            type: item.type,
            data: item.data,
            name: item.name,
            yAxisIndex: 0,
            // barWidth: item.barWidth,
            barMaxWidth: item.barWidth,
            barGap: 0.5,
            itemStyle: {
              color: item.color,
              borderRadius: [2, 2, 0, 0]
            },
            // cursor: "normal",
            z: 0
          };
        }),
      ...yData
        .filter((item) => item.type === 'line')
        .map((item) => {
          return {
            type: item.type,
            data: item.data,
            name: item.name,
            yAxisIndex: 1,
            lineStyle: {
              color: item.color
            },
            showSymbol: false,
            symbolSize: 10,
            z: 2
          };
        })
    ]
  };
};
